package com.trkj.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.trkj.dao.jpa.IYzrMedPurchDAO;
import com.trkj.dao.jpa.IYzrMedPurchDetDAO;
import com.trkj.dao.jpa.IYzrMedicineDAO;
import com.trkj.dao.jpa.IYzrSupplierDAO;
import com.trkj.dao.jpa.IYzrTbstaffDAO;
import com.trkj.pojos.Tbstaff;
import com.trkj.pojos.YzrMedPurch;
import com.trkj.pojos.YzrMedPurchDet;
import com.trkj.pojos.YzrMedicine;
import com.trkj.pojos.YzrSupplier;
import com.trkj.vo.YzrMedPlanVo;
import com.trkj.vo.YzrMedPurchDetVo;
import com.trkj.vo.YzrMedPurchVo;

@Service
@Transactional
public class YzrPurchPlanService {

	@Autowired
	private IYzrMedPurchDAO yzrMedPurchDAO;
	@Autowired
	private IYzrMedPurchDetDAO yzrMedPurchDetDAO;
	@Autowired
	private IYzrTbstaffDAO yzrTbstaffDAO;
	@Autowired
	private IYzrSupplierDAO yzrSupplierDAO;
	@Autowired
	private IYzrMedicineDAO yzrMedicineDAO;
	
	
	//审批采购计划，保存数据
	public void approvalPlan(String shenpiState, String remark, String planId){
		YzrMedPurch purch = yzrMedPurchDAO.findOne(planId);
		purch.setPurchAutditState(shenpiState);//状态
		purch.setPurchRemark(remark);//备注
		purch.setPurchAutditTime(new Date());//审批时间
		yzrMedPurchDAO.save(purch);
	}
	
	/**
	 * 根据当前登录的用户，查找出待该用户审批的采购计划
	 * @param page
	 * @param rows
	 * @param staffId
	 * @return
	 */
	public Map<String, Object> queryPurchPlanByLoginUser(int page,int rows,Long staffId){
		PageRequest pr = new PageRequest(page - 1, rows);
		//根据   审批人=“staffId” and 审批状态=“待审批”   查找出采购计划
		List<YzrMedPurch>  list = yzrMedPurchDAO.findPlanByAutdit(new BigDecimal(staffId), pr);
		System.out.println("审批list:"+list.size());
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", list.size());
		map.put("rows", medPurchListToVo(list));
		return map;
	}
	
	/**
	 * 修改采购计划
	 * @param purchId
	 * @param purchTitle
	 * @param purchMakepeople
	 * @param purchAutdit
	 * @param purchArriivalDate
	 * @param purchZdTime
	 * @param medPurchDets
	 */
	public void editPurchPlan(String purchId,String purchTitle,String purchMakepeople,
							String purchAutdit,Date purchArriivalDate,Date purchZdTime,
							YzrMedPlanVo  medPurchDets){
		/*
		 * 1.根据计划编号找到之前的采购信息，依次覆盖
		 */
		YzrMedPurch purch = yzrMedPurchDAO.findOne(purchId);
		purch.setPurchTitle(purchTitle);
		purch.setPurchArriivalDate(purchArriivalDate);
		purch.setPurchZdTime(purchZdTime);
		purch.setPurchAutdit(new BigDecimal(purchAutdit));
		purch.setPurchMakepeople(new BigDecimal(purchMakepeople));
		yzrMedPurchDAO.save(purch);

		
		//2.找出数据库内该计划单号下的计划明细,删除
		List<YzrMedPurchDet> srcPurDet = yzrMedPurchDetDAO.findByPurchId2(purchId);
		yzrMedPurchDetDAO.delete(srcPurDet);

		//3.判断计划明细编号是否存在，如果存在就覆盖，不存在就生成一个编号，将信息存入
		List<YzrMedPurchDetVo> list = medPurchDets.getMedPurchDets();
		
		if(list != null){
			for(YzrMedPurchDetVo purDet:list){
				
				System.err.println("输出："+purDet.getPurchDetId().length());
				
				if(purDet.getPurchDetId().length()>1){
					
					System.err.println("旧的");
					
					YzrMedPurchDet temp =  new YzrMedPurchDet();
					temp.setPurchDetId(purDet.getPurchDetId());
					temp.setPurchDetPurchId(purchId);//采购id
					temp.setPurchDetMedId(purDet.getMedId());
					temp.setPurchDetGuige(purDet.getPurchDetGuige());
					temp.setPurchDetUnit(purDet.getPurchDetUnit());
					temp.setPurchDetNumber(purDet.getPurchDetNumber());
					temp.setPurchDetSupId(purDet.getSupId());
					temp.setPurchDetYijiMoney(purDet.getPurchDetYijiMoney());
					yzrMedPurchDetDAO.save(temp);
				}else{
					
					System.err.println("新的");
					//生成编号
					YzrEntityService entityService = new YzrEntityService();
					String year = getNowDate();
					String nameDet = "PD-" + year;	
					String n = yzrMedPurchDetDAO.findID(nameDet);	
					YzrMedPurchDet temp = new YzrMedPurchDet();
					String name = entityService.getId(nameDet, n);
					
					temp.setPurchDetId(name);//明细id
					temp.setPurchDetPurchId(purchId);//采购id
					temp.setPurchDetMedId(purDet.getMedId());
					temp.setPurchDetGuige(purDet.getPurchDetGuige());
					temp.setPurchDetUnit(purDet.getPurchDetUnit());
					temp.setPurchDetNumber(purDet.getPurchDetNumber());
					temp.setPurchDetSupId(purDet.getSupId());
					temp.setPurchDetYijiMoney(purDet.getPurchDetYijiMoney());
					
					yzrMedPurchDetDAO.save(temp);
				}
			}
		}
		
	}
	
	
	/**
	 * 批量删除采购计划及采购详情
	 * @param list 
	 */
	public void delMedPurch(String[] list){
		if(list != null){
			for(String p: list){
				//删除采购计划
				yzrMedPurchDAO.delete(p);
				//删除采购计划明细
				List<YzrMedPurchDet> pList=yzrMedPurchDetDAO.findByPurchId2(p);
				yzrMedPurchDetDAO.delete(pList);
			}
		}
		
	}
	
	/**
	 * 返回根据采购计划id查找出的计划明细的条数
	 * @param purchId
	 * @return
	 */
	public long queryPlanDetCount(String purchId){
		return yzrMedPurchDetDAO.findByCount(purchId);
	}
	
	/**
	 * 根据采购计划id查找出采购计划和计划明细
	 * @param purchId
	 * @return
	 */
	public YzrMedPlanVo queryAllPlanAndPlanDet(String purchId){
		//找到计划
		YzrMedPurch purch = yzrMedPurchDAO.findOne(purchId);
		
		//找到明细
		List<YzrMedPurchDet> list = yzrMedPurchDetDAO.findByPurchId2(purchId);
		
		List<YzrMedPurchDetVo> listVo = new ArrayList<>();
		//明细转Vo
		for(YzrMedPurchDet purchDet: listVo){
			YzrMedPurchDetVo purchDetVo = purchDetPoToVo(purchDet);
			listVo.add(purchDetVo);
		}
		
		YzrMedPlanVo planVo = new YzrMedPlanVo();
		System.err.println("采购计划"+purch.getPurchId()+purch.getPurchTitle());
		//复制属性
		planVo.setMedPurch(purch);//采购计划		
		planVo.setMedPurchDets(listVo);//采购计划明细
			
		return planVo;
	}
	
	/**
	 * 根据采购id查找采购明细(分页)
	 * @param page
	 * @param rows
	 * @param purchId
	 * @return
	 */
	public Map<String, Object> queryAllPurchDet(int page, int rows,String purchId){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrMedPurchDet> list = yzrMedPurchDetDAO.findAll(purchId,pr);
		long total = yzrMedPurchDetDAO.findByCount(purchId);
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", total);
		map.put("rows", PurchDetListToVo(list));
		return map;
	}
	
	/**
	 * 根据采购id查找采购明细（不分页）
	 * @param purchId
	 * @return
	 */
	public List<YzrMedPurchDetVo> queryAllPurchDet2(String purchId){
		List<YzrMedPurchDet> list = yzrMedPurchDetDAO.findAll2(purchId);
		System.err.println("list的长度:"+list.size());
		PurchDetListToVo(list);		
		return PurchDetListToVo(list);
	}
	
	/**
	 * 将YzrMedPurchDet的集合转换成YzrMedPurchDetVo的List集合
	 * @param list
	 * @return
	 */
	private List<YzrMedPurchDetVo> PurchDetListToVo(List<YzrMedPurchDet> list){
		//System.err.println("list的长度:"+list.size());
		if(list == null) return null;
		List<YzrMedPurchDetVo> listVo = new ArrayList<>();
		
		for(YzrMedPurchDet purchDet: list){
			YzrMedPurchDetVo purchDetVo = purchDetPoToVo(purchDet);
			listVo.add(purchDetVo);
		}
		return listVo;
	}
	
	/**
	 * 药品采购计划明细属性复制
	 * @param purchDet
	 * @return
	 */
	public YzrMedPurchDetVo purchDetPoToVo(YzrMedPurchDet purchDet){
		YzrMedPurchDetVo purchDetVo = new YzrMedPurchDetVo();
		purchDetVo.setPurchDetId(purchDet.getPurchDetId());
		purchDetVo.setPurchDetGuige(purchDet.getPurchDetGuige());
		purchDetVo.setPurchDetNumber(purchDet.getPurchDetNumber());
		purchDetVo.setPurchDetPurchId(purchDet.getPurchDetPurchId());
		purchDetVo.setPurchDetUnit(purchDet.getPurchDetUnit());
		purchDetVo.setPurchDetYijiMoney(purchDet.getPurchDetYijiMoney());
		purchDetVo.setPurchDetMedId(purchDet.getPurchDetMedId());
		purchDetVo.setPurchDetSupId(purchDet.getPurchDetSupId());
		
		String medId = purchDet.getPurchDetMedId();
		String supId = purchDet.getPurchDetSupId();
		
		if(medId != null){		
			YzrMedicine med = yzrMedicineDAO.findOne(medId);
			purchDetVo.setMedId(med==null?null:med.getMedId());
			purchDetVo.setMedName(med==null?null:med.getMedName());			
		}
		
		if(supId != null){			
			YzrSupplier sup = yzrSupplierDAO.findOne(supId);		
			purchDetVo.setSupId(sup==null?null:sup.getSupId());
			purchDetVo.setSupName(sup==null?null:sup.getSupName());
		}
		return purchDetVo;
	}
	
	
/***********************************采购计划*************************************************/	
	
	/**
	 * 根据采购状态查找采购计划
	 * @param state
	 * @param page
	 * @param rows
	 * @return
	 */
	public Map<String, Object> queryByPurchState(String state,int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrMedPurch> list = yzrMedPurchDAO.findByPurchState(state, pr);
		long total = yzrMedPurchDAO.findByPurchStateCount(state);
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", total);
		map.put("rows", medPurchListToVo(list));
		return map;
	}
	
	
	/**
	 * 根据标题查找采购计划
	 * @param title
	 * @param page
	 * @param rows
	 * @return
	 */
	public Map<String, Object> queryByTitle(String title,int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrMedPurch> list = yzrMedPurchDAO.findByTitle(title, pr);
		long total = yzrMedPurchDAO.findByTitleCount(title);
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", total);
		map.put("rows", medPurchListToVo(list));
		return map;
	}
	
	
	/**
	 * 根据状态查找采购计划
	 * @param state
	 * @param page
	 * @param rows
	 * @return
	 */
	public  Map<String, Object> queryByAutditState(String state,int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrMedPurch> list = yzrMedPurchDAO.findByAutditState(state, pr);
		long total = yzrMedPurchDAO.findByStateCount(state);
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", total);
		map.put("rows", medPurchListToVo(list));
		return map;
	}
	
	
	/**
	 * 根据制定人查找采购计划
	 * @param purchName
	 * @param page
	 * @param rows
	 * @return
	 */
	public  Map<String, Object> queryByPurchName(String purchName,int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrMedPurch> list = yzrMedPurchDAO.findByPurchName(purchName, pr);
		long total = yzrMedPurchDAO.findByNameCount(purchName);
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", total);
		map.put("rows", medPurchListToVo(list));
		return map;
	}
	
	/**
	 * 根据id查找采购计划
	 * @param purchId
	 * @return
	 */
	public 	YzrMedPurchVo queryMedPurchById(String purchId){
		YzrMedPurch purch = yzrMedPurchDAO.findOne(purchId);
		return medPurchPoToVo(purch);
	}
	
	/**
	 * 分页查询药品采购计划采购计划信息
	 * @param page
	 * @param rows
	 * @return
	 */
	public Map<String, Object> queryAllMedPurch(int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrMedPurch> list = yzrMedPurchDAO.findAll(pr);
		long total = yzrMedPurchDAO.count();
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", total);
		map.put("rows", medPurchListToVo(list));
		return map;
	}
	
	/**
	 * 将YzrMedPurch的集合转换成YzrMedPurchVo的List集合
	 * @param list
	 * @return
	 */
	private List<YzrMedPurchVo> medPurchListToVo(List<YzrMedPurch> list){
		if(list == null) return null;
		List<YzrMedPurchVo> listVo = new ArrayList<>();
		
		for(YzrMedPurch store: list){
			YzrMedPurchVo storeVo = medPurchPoToVo(store);
			listVo.add(storeVo);
		}
		return listVo;
	}
	/**
	 * 药品采购计划属性复制
	 * @param medPurch
	 * @return
	 */
	public YzrMedPurchVo medPurchPoToVo(YzrMedPurch medPurch){
		
		YzrMedPurchVo medPurchVo = new YzrMedPurchVo();
		medPurchVo.setPurchId(medPurch.getPurchId());
		medPurchVo.setPurchTitle(medPurch.getPurchTitle());
		medPurchVo.setPurchZdTime(medPurch.getPurchZdTime());
		medPurchVo.setPurchArriivalDate(medPurch.getPurchArriivalDate());
		medPurchVo.setPurchAutditState(medPurch.getPurchAutditState());
		medPurchVo.setPurchAutditTime(medPurch.getPurchAutditTime());
		medPurchVo.setPurchState(medPurch.getPurchState());
		medPurchVo.setPurchMakepeople(medPurch.getPurchMakepeople());
		medPurchVo.setPurchAutdit(medPurch.getPurchAutdit());
		medPurchVo.setPurchRemark(medPurch.getPurchRemark());
		
		//获取制定人id
		BigDecimal zdr = medPurch.getPurchMakepeople();
		//获取审批人id
		BigDecimal spr = medPurch.getPurchAutdit();
		
		if(zdr != null){		
			long sId = zdr.longValue();		
			Tbstaff staff = yzrTbstaffDAO.findOne(sId);	
			medPurchVo.setStaffNo(staff==null?0:staff.getStaffNo());;
			medPurchVo.setStaffName(staff==null?null:staff.getStaffName());
		}		
		if(spr != null){		
			long sId = spr.longValue();		
			Tbstaff staff = yzrTbstaffDAO.findOne(sId);	
			medPurchVo.setStaffNo(staff==null?0:staff.getStaffNo());;
			medPurchVo.setStaffNameSp(staff==null?null:staff.getStaffName());
		}
		return medPurchVo;
	}
	
	
	
	
	/**
	 * 制定采购计划
	 * @param medPlanVo
	 */
	public void doMedPlan(YzrMedPlanVo medPlanVo){
		// 获取年份
		String year = getNowDate();
		//拼接
		String name = "PL-" + year;	
		String nameDet = "PD-" + year;	
		String n = yzrMedPurchDAO.findID(name);	
		//System.out.println("从数据库中读取的最大采购计划编号："+n);

		
		//生成采购计划表编号
		YzrEntityService entityService = new YzrEntityService();
		String purId = entityService.getId(name, n);
		//保存编号
		medPlanVo.getMedPurch().setPurchId(purId);
		medPlanVo.getMedPurch().setPurchZdTime(new Date());
		medPlanVo.getMedPurch().setPurchAutditState("待审核");
		medPlanVo.getMedPurch().setPurchState("未采购");
		//保存采购计划
		yzrMedPurchDAO.save(medPlanVo.getMedPurch());
		
		//保存采购计划明细
		List<YzrMedPurchDetVo> list = medPlanVo.getMedPurchDets();
		System.err.println("list大小："+list.size());
		if(list != null){
			for(YzrMedPurchDetVo det: list){
				
				YzrMedPurchDet det2 = new YzrMedPurchDet();
				
				//获取明细表中最大编号
				String nDet = yzrMedPurchDetDAO.findID(nameDet);
				System.out.println("从数据库中读取的最大采购计划明细编号："+nDet);
				
				det2.setPurchDetMedId(det.getPurchDetMedId());//药品id
				det2.setPurchDetYijiMoney(det.getPurchDetYijiMoney());//预计金额
				det2.setPurchDetSupId(det.getPurchDetSupId());//供应商id
				det2.setPurchDetNumber(det.getPurchDetNumber());//数量
				det2.setPurchDetUnit(det.getPurchDetUnit());//单位
				det2.setPurchDetGuige(det.getPurchDetGuige());//规格
				det2.setPurchDetId(entityService.getId(nameDet, nDet));//明细id
				det2.setPurchDetPurchId(entityService.getId(name, n));//采购id
				//保存明细
				yzrMedPurchDetDAO.save(det2);
			}
		}		
	}
	
	/**
	 * 格式化日期
	 * @return
	 */
	public static String getNowDate() {
		  Date currentTime = new Date();
		  SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		  String dateString = formatter.format(currentTime);
		  return dateString;
	}
}
